
//
//  QGNetworkManager+Extension.swift
//  斯威夫特微博
//
//  Created by youyoumacmini3 on 2017/7/7.
//  Copyright © 2017年 youyoumacmini3. All rights reserved.
//

import Foundation


// MARK: - 封装新浪微博网络请求方法
extension QGNetworkManager {
    
    /// 加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调[list:微博字典数组, 是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String :Any]]?, _ isSuccess: Bool)->()) {
        
      
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
     
        // 虽然此处我用的是Any ；如果是AnyObject
        // swift中 Int可以转换成 AnyObject /但是 Int64不行
        let params = ["since_id": since_id, "max_id": max_id > 0 ? max_id - 1 : 0]
        
        tokenRequest(URLString: urlStr, parameters: params) { (json, isSuccess) in
            
            // 从json中获取 statuses 字典数组
            // 如果 as? 失败， result = nil
            if json != nil{
                let result =  (json as! NSDictionary)["statuses"] as? [[String: Any]]
                
                completion(result,isSuccess)
            }
        }
    }
    
    
    /// 返回微博的未读数量(此处瞎写的uid和刀的unread url 竟然出来数据了呵呵)
    func unreadCount(completion:@escaping (_ count: Int)->()) {
        
      guard let uid = userAccount.uid else { return  }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            
            //print("稀里糊涂的数据出来了？？\(json!)")
            
            let dic = json as? [String: Any]
            let count = dic?["status"] as? Int
            completion(count ?? 0)
        }
        
    }
    
}

// MARK: - 发布微博
extension QGNetworkManager {

    /// 发布微博
    ///
    /// - Parameters:
    ///   - text: 发布的文本
    ///   - image: 上传的image（）可为 nil - 为nil时，发布纯文本微博
    ///   - completion: 完成回调
    func postStatus(text: String, image: UIImage?, completion: @escaping (_ result: [String: Any]?, _ isSuccess: Bool)->()) -> () {
        
        // 1. url
        let urlString: String
        // 其实下面链接都不能用了（废弃了）
        if image == nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        // 2. 参数字典
        let params = ["status": text]
        
        // 3. 如果图像不为空。需要设置 name 和 data
        var name: String?
        var data: Data?
        
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
            
        }
        
        // 3. 发起网络请求
        tokenRequest(method: .POST, URLString: urlString, parameters: params, name: name, data: data) { (json, isSuccess) in
            completion(json as? [String: Any], isSuccess)
        }
    }
}

// MARK: - 用户信息
extension QGNetworkManager {
    
    // 加载当前用户信息 - 用户登录后立即执行
    func loadUserInfo(completion:@escaping(_ dic: [String: Any])->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        
        // 发起网络请求
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            //完成回调
            completion((json as? [String: Any]) ?? [:])
        }
    }
}


// MARK: - OAuth相关方法
extension QGNetworkManager {
    
    /// 加载 AccessToken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调
    func loadAccessToken(code: String ,completion:@escaping(_ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":WBAppKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURI]
        // 发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            print(json)
            
            //如果请求失败，对用户账户不会有任何影响
            // 直接 用字典设置 userAccount属性
            self.userAccount.yy_modelSet(with: (json as? [AnyHashable : Any]) ?? [:])
            
            //加载当前用户信息
            self.loadUserInfo(completion: { (dic) in
                print(dic)
                
                // 使用用户信息字典设置用户账户信息（昵称和头像地址）
                self.userAccount.yy_modelSet(with: dic)
                //保存模型
                self.userAccount.saveAccount()
                
                print(self.userAccount)
            })
            
            // 用户信息加载完成再，完成回调
            completion(isSuccess)
        }
        
        
    }
}


